const jwt = require('jsonwebtoken')
const { JWT_SECRET } = require('../config/config.default')
const { success,error } = require('../utils/response')
const auth = async (ctx,next) => {
  const { authorization = '' } = ctx.request.header
  const token = authorization.replace('Bearer ','')
  try{
    const user = jwt.verify(token,JWT_SECRET)
    ctx.state.user = user
  } catch(err){
    switch(err.name){
      case 'TokenExpiredError':
        return error(ctx,null,'token过期')
      case 'JsonWebTokenError':
        return error(ctx,null,'无效token')
    }
  }
  await next()
}
const hasAdminPermission = async (ctx,next)=>{
  const { isAdmin } = ctx.state.user.dataValues
  console.log(isAdmin)
  if(isAdmin != 0){
    return error(ctx,null,'没有权限')
  }
  await next()
}
module.exports = {
  auth,
  hasAdminPermission
}